/* 
 * File:   LedsHandler.cpp
 * Author: Arno
 * 
 * Created on 15 juni 2012, 13:04
 */

#include "LedsHandler.h"

void LedsHandler::main(void) {

    std::cout << "\n Leds starting ";

    state = Displaying;

    for (;;) {

        RTOS::event ledsWaitable = wait(ledFlag + blinkDurTimer + blinkFreqTimer);
        
        if (ledFlag == ledsWaitable) {
            current = ledPool.read();
            frequency = current.frequency;
            duration = current.duration;
            blinkDurTimer.set(duration S);
            ledFlag.clear();
            ledsOn = true;
            state = Blinking;
        } else if (blinkFreqTimer == ledsWaitable) {
            ledsOn = !ledsOn;
        } else if (blinkDurTimer == ledsWaitable) {
            if (ledsOn) {
                Led.ledsOn(currLives);
                ledsOn = false;
            }
            state = Displaying;
        }

        switch (state) {

            case Displaying:
                
                currLives = livesPool.read();
                Led.ledsOn(currLives);
                
                break;

            case Blinking:

                blinkFreqTimer.set(frequency MS);

                if (ledsOn) {
                    Led.ledsOn(0xFF);
                } else {
                    Led.ledsOff(0);
                }
                break;
        }
    }
}

void LedsHandler::blink(int dur, int freq) {

    temp.duration = dur;
    temp.frequency = freq;
    ledPool.write(temp);

    ledFlag.set();

    std::cout << "\n written to Led - pool: "
            << std::dec << freq
            << " Interval and for "
            << std::dec << dur
            << " seconds ";
}

void LedsHandler::setLives(int lives) {
    if (lives >= 1) {
        int ledLives = 0xFF;
        int livesShown = 0;
        int amountLedsMoved = 8 - lives;
        int i = 0;
        for(i; i < amountLedsMoved; i++){
                livesShown = ledLives >> amountLedsMoved;
        }
        livesPool.write(livesShown);
        std::cout << "\n written to livesPool: " << std::dec << ledLives << " and lives is " << std::dec << lives;
    } else {
        livesPool.write(0);
        std::cout << "\n written to livesPool: " << std::dec << 0;
    }
}